package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @Author：yyj
 * @Package：com.atguigu.lease.common.utils
 * @Project：project01
 * @name：JwtUtil
 * @Date：2024/11/21 16:26
 * @Filename：JwtUtil
 */
public class JwtUtil {

    private static SecretKey secretKey = Keys.hmacShaKeyFor("0RCXuEFumbZwXiarAni2gaMPMTByFisb".getBytes());

    public static String setToken(String username, Long userId) {
        String compact = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 3600000))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();
        return compact;
    }


    public static Claims parseToken(String token) {

        if (token==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        try {
            JwtParser build = Jwts.parserBuilder().setSigningKey(secretKey).build();
            Jws<Claims> claimsJws = build.parseClaimsJws(token);
            return claimsJws.getBody();
        }catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }

    }

    public static void main(String[] args) {
        System.out.println(setToken("abc", 12l));
    }
}
